package hs.bank.Web.Service;

import hs.bank.Data.CardMapper;
import hs.bank.Data.UserMapper;
import hs.bank.Entity.Card;
import hs.bank.Entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("registerNewCard")
public class RegisterNewCard {

    private UserMapper userMapper;
    private CardMapper cardMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Autowired
    public void setCardMapper(CardMapper cardMapper) {
        this.cardMapper = cardMapper;
    }

    @GetMapping
    public String registerNewCard(Model model) {
        int maxCardNumber = cardMapper.maxCardNumber();
        int newCardNumber = maxCardNumber + 1;

        try {
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            int userId = user.getUserId();
            cardMapper.save(new Card(newCardNumber, userId));
            model.addAttribute("newCardNumber", newCardNumber);
            model.addAttribute("error", false);
            return "registerNewCard";
        } catch (Exception e) {
            model.addAttribute("error", true);
            return "registerNewCard";
        }
    }

}
